package com.examstack.portal.controller.action;

import com.examstack.common.domain.exam.Message;
import com.examstack.common.domain.user.User;
import com.examstack.common.util.StandardPasswordEncoderForSha1;
import com.examstack.common.util.email.MailUtil;
import com.examstack.portal.security.UserInfo;
import com.examstack.portal.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

@Controller
public class UserAction {
    @Autowired
    private UserService userService;
    public static final String KAPTCHA_SESSION_KEY = "rand";

    /**
     * 添加用户
     *
     * @param user
     * @param user
     *            如果添加的用户为学员，必须指定groupId。如果添加的用户为教师，则groupId为任意数字
     * @return
     */
    @RequestMapping(value = { "/add-user" }, method = RequestMethod.POST)
    public @ResponseBody Message addUser(@RequestBody User user,HttpServletRequest request) {
        user.setCreateTime(new Date());

        String password = user.getPassword() + "{" + user.getUserName().toLowerCase() + "}";
        PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
        String resultPassword = passwordEncoder.encode(password);
        user.setPassword(resultPassword);
        /*user.setEnabled(true);*/
        user.setEnabled(false);
        user.setCreateBy(-1);
        user.setUserName(user.getUserName().toLowerCase());
        Message message = new Message();

        HttpSession session = request.getSession();
        String sessionValidateCode = this.obtainSessionValidateCode(session);
        //将验证码session清空
        session.setAttribute(KAPTCHA_SESSION_KEY, null);
        String validateCodeParameter = user.getCode();
        if(StringUtils.isEmpty(validateCodeParameter) || !sessionValidateCode.equalsIgnoreCase(validateCodeParameter)){
            //System.out.println("验证码错误！sessionValidateCode=" + sessionValidateCode + "  validateCodeParameter=" + validateCodeParameter);
            message.setResult("code");
            message.setMessageInfo("验证码错误");
            return message;
        }

        try {
            userService.addUser(user, "ROLE_STUDENT", 0, userService.getRoleMap());
        } catch (Exception e) {
            // TODO Auto-generated catch block

            if(e.getMessage().contains(user.getUserName())){
                message.setResult("duplicate-username");
                message.setMessageInfo("重复的用户名");
            } else if(e.getMessage().contains(user.getNationalId())){
                message.setResult("duplicate-national-id");
                message.setMessageInfo("重复的身份证");
            } else if(e.getMessage().contains(user.getEmail())){
                message.setResult("duplicate-email");
                message.setMessageInfo("重复的邮箱");
            } else if(e.getMessage().contains(user.getPhoneNum())){
                message.setResult("duplicate-phone");
                message.setMessageInfo("重复的电话");
            } else{
                message.setResult(e.getCause().getMessage());
                e.printStackTrace();
            }
        }
        return message;
    }

    @RequestMapping(value = { "/student/update-user" }, method = RequestMethod.POST)
    public @ResponseBody Message updateUser(@RequestBody User user) {

        UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        String password = user.getPassword() + "{" + user.getUserName() + "}";
        PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
        String resultPassword = "";
        if(user.getPassword() != null)
            resultPassword = "".equals(user.getPassword().trim()) ? "" : passwordEncoder.encode(password);
        user.setPassword(resultPassword);
        user.setEnabled(true);
        Message message = new Message();
        try {
            userService.updateUser(user, null);
            userInfo.setTrueName(user.getTrueName());
            userInfo.setEmail(user.getEmail());
            userInfo.setNationalId(user.getNationalId());
            userInfo.setPhoneNum(user.getPhoneNum());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            if(e.getMessage().contains(user.getUserName())){
                message.setResult("duplicate-username");
                message.setMessageInfo("重复的用户名");
            } else if(e.getMessage().contains(user.getNationalId())){
                message.setResult("duplicate-national-id");
                message.setMessageInfo("重复的身份证");
            } else if(e.getMessage().contains(user.getEmail())){
                message.setResult("duplicate-email");
                message.setMessageInfo("重复的邮箱");
            } else if(e.getMessage().contains(user.getPhoneNum())){
                message.setResult("duplicate-phone");
                message.setMessageInfo("重复的电话");
            } else{
                message.setResult(e.getCause().getMessage());
                e.printStackTrace();
            }


        }
        return message;
    }

    @RequestMapping(value = { "/student/change-pwd" }, method = RequestMethod.POST)
    public @ResponseBody Message changePassword(@RequestBody User user){
        Message message = new Message();
        UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();
        try{
            User pwd = userService.getPassword(userInfo.getUsername());
            //新密码
            String password = user.getPassword() + "{" + userInfo.getUsername() + "}";
            //原密码
            String oldPassword = user.getOldPwd() + "{" + userInfo.getUsername() + "}";
            PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
            String resultPassword = passwordEncoder.encode(password);
            String resultOldPwd = passwordEncoder.encode(oldPassword);
            if (!resultOldPwd.equals(pwd.getPassword())){
                message.setResult("fail");
                return message;
            }
            //String oldPwd = resultOldPwd;
            user.setOldPwd(resultOldPwd);
            user.setPassword(resultPassword);
            user.setUserName(userInfo.getUsername());
            userService.updateUserPwd(user, null);
        }catch(Exception e){
            e.printStackTrace();
            message.setResult(e.getClass().getName());
        }

        return message;
    }

    //生成的验证码
    protected String obtainSessionValidateCode(HttpSession session){
        Object obj = session.getAttribute(KAPTCHA_SESSION_KEY);
        return null == obj ? "" : obj.toString();
    }

    /**
     * 发送邮箱验证码
     * @param request
     * @return
     */
    @RequestMapping(value = { "/send-mail-code" }, method = RequestMethod.POST)
    public @ResponseBody Message sendMailCode(@RequestBody Map<String,String> map, HttpServletRequest request){
        Message message = new Message();
        String toMail = map.get("mail");
        //1、检查邮箱是否存在
        if ("".equals(toMail) || toMail.isEmpty()){
            message.setResult("fail");
            message.setMessageInfo("请正确填写邮箱");
            return message;
        }
        //查找邮箱是否存在且激活
        User user = userService.findUserByEmail(toMail);
        if (user.getEmail()==null){
            message.setResult("fail");
            message.setMessageInfo("邮箱未注册");
            return message;
        }
        //2、发送验证码
        String mailCode = this.makeRand();
        boolean sendRes = MailUtil.sendMail(mailCode, toMail);
        if (!sendRes){
            message.setResult("fail");
            message.setMessageInfo("验证码发送失败");
            return message;
        }
        message.setResult("success");
        message.setMessageInfo("验证码发送成功");
        //4、用session保存验证码
        request.getSession().setAttribute(KAPTCHA_SESSION_KEY, mailCode);
        return message;
    }

    /**
     * 检查邮箱验证码是否正确
     * @param request
     * @return
     */
    @RequestMapping(value = { "/validate-mail-code" }, method = RequestMethod.POST)
    public @ResponseBody Message validateMailCode(@RequestBody Map<String,String> map,HttpServletRequest request){
        Message msg = new Message();
        //1、检查验证码是否正确
        String validateCode = map.get("validate_code");
        //String toMail = map.get("mail");
        Object objCode = request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        if (objCode == null || objCode.toString().isEmpty() || !(objCode.toString()).equals(validateCode)){
            msg.setMessageInfo("验证码错误");
            msg.setResult("fail");
            return msg;
        }
        msg.setResult("success");
        msg.setMessageInfo("验证码正确");
        request.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        return msg;
    }
    @RequestMapping(value = {"/update-pwd-by-mail"}, method = RequestMethod.POST)
    public @ResponseBody Message updatePwdByMail(@RequestBody User user){
        Message msg = new Message();
        //获取用户名
        User users = userService.findUserByEmail(user.getEmail());
        if (users.getUserName() == null || users.getUserName().isEmpty()){
            msg.setResult("fail");
            msg.setMessageInfo("密码修改失败");
            return msg;
        }
        String resultPwd = user.getPassword() + "{"  + users.getUserName() + "}";
        user.setPassword(new StandardPasswordEncoderForSha1().encode(resultPwd));
        try{
            userService.updatePwdByMail(user);
        } catch (Exception e){
            msg.setResult("fail");
            msg.setMessageInfo("密码修改失败");
            String cause = e.getCause().getMessage();
            throw new RuntimeException(cause);
        }
        msg.setResult("success");
        msg.setMessageInfo("密码修改成功");
        return msg;
    }
    private String makeRand(){
        String str = (Math.random())+"";
        return str.substring(2,6);
    }
}
